let editFbId = '',fbGridSelector = "#gridTable";
jQuery(function($) {
    //初始化日期选择控件
    $('.date-picker').datepicker({
        todayHighlight: true,
        language: 'cn',
        autoclose: true
    }).next().on(ace.click_event, function(){
        $(this).prev().focus();
    });
    let pagerSelector = "#gridPager";
    let parentColumn = $(fbGridSelector).closest('[class*="col-"]');
    //resize to fit page size
    $(window).on('resize.jqGrid', function () {
        $(fbGridSelector).jqGrid( 'setGridWidth', parentColumn.width());
    });

    //resize on sidebar collapse/expand
    $(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
        if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
            //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
            setTimeout(function() {
                $(fbGridSelector).jqGrid( 'setGridWidth', parentColumn.width());
            }, 20);
        }
    });

    jQuery(fbGridSelector).jqGrid({
        url : '/sameCityFeedback/listFeedback',
        jsonReader : {
            root: "list",    //数据集
            page: 'pageNum', //当前页号
            total: 'pages',  //总页数
            records: "total" //总记录数
        },
        rownumbers: true,
        mtype : "post",
        datatype: 'json',
        height: getGridHeight(),
        colNames:['ID','反馈人联系方式','反馈内容','反馈类型', '反馈时间','处理人','处理时间','处理状态','处理结果'],
        colModel:[
            {name:'fbId',index:'fbId', width:30},
            {name:'fbContact',index:'fbContact',width:80},
            {name:'fbContent',index:'fbContent',formatter: function(cellvalue, options, rowObj){
                return '<a style="cursor: pointer;" onclick="showFeedback(' +
                    JSON.stringify(rowObj).replace(/"/g,"&quot;") + ')">' + htmlEncodeByRegExp(cellvalue) + '</a>';
            }},
            {name:'fbType',index:'fbType', width:60,formatter: function(fbTypeValue){
                let typeArr = ['反馈','投诉','客服','其它'];
                return fbTypeValue > 3 || fbTypeValue < 0 ? fbTypeValue : typeArr[fbTypeValue];
            }},
            {name:'fbCreateDate',index:'fbCreateDate',width: 70},
            {name:'dealPeople',index:'dealPeople',width: 70},
            {name:'dealDate',index:'dealDate',width: 70},
            {name:'dealStatus',index:'dealStatus',width: 80,formatter: function(statusValue){
                let statusArr = ['未处理','处理中','已处理'];
                return statusValue > 2 || statusValue < 0 ? statusValue : statusArr[statusValue];
            }},
            {name:'dealResult',index:'dealResult'}
        ],
        viewrecords : true,
        rowNum:10,
        rowList:[10,20,30],
        pager : pagerSelector,
        altRows: true
    });
    //trigger window resize to make the grid get the correct size
    $(window).triggerHandler('resize.jqGrid');

    //navButtons
    jQuery(fbGridSelector).jqGrid('navGrid',pagerSelector,
        { 	//navbar options
            edit: false,
            editicon : 'ace-icon fa fa-pencil blue',
            add: false,
            addicon : 'ace-icon fa fa-plus-circle purple',
            del: false,
            delicon : 'ace-icon fa fa-trash-o red',
            search: true,
            searchicon : 'ace-icon fa fa-search orange',
            refresh: true,
            refreshicon : 'ace-icon fa fa-refresh green',
            view: false,
            viewicon : 'ace-icon fa fa-search-plus grey',
        }
    );

    //replace icons with FontAwesome icons like above
    function updatePagerIcons(table) {
        let replacement = {
            'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
        };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
            let icon = $(this);
            let $class = $.trim(icon.attr('class').replace('ui-icon', ''));
            if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
        });
    }
    $('#closeFbForm').click(function () {
        closeFbForm();
    });
    //查询按钮
    $('#btnQueryFb').click(function () {
        reloadFeedback();
    });
    $('#imgMax').click(function () {
        $(this).hide();
    });
    $('#btnFbDeal').click(function () {
        dealFeedback();
    });
});

/**
 * 查看反馈信息详情
 * @param fbObj 反馈信息对象
 */
function showFeedback(fbObj) {
    $('.page-mask,.feedback-from').show();
    //设置表单高度
    $('#fbDetailForm').css('height',$('body').height() * 0.8 + 'px');
    for (let f in fbObj){
        $('#' + f).val(fbObj[f]);
    }
    editFbId = fbObj.fbId;
    let dealStatus = fbObj.dealStatus;
    $('#fbType' + fbObj.fbType).attr('checked','checked');
    $('#dealStatus' + dealStatus).attr('checked','checked');
    let imgPathName = isNull(fbObj.imgPathName) ? '' : fbObj.imgPathName;
    let imgPathArr = imgPathName.split('|'), imgLabelArr = [];
    for (let g = 0; g < imgPathArr.length; g ++){
        imgLabelArr.push('<img width="80" height="80" src="/images/feedback/' + imgPathArr[g] + '">');
    }
    $('#fbImgList').append(imgLabelArr.length > 0 ? imgLabelArr.join('') : '无图片');
    //图片点击最大化
    $('#fbImgList img').click(function () {
        let imgSrc = $(this).attr('src');
        $('#imgMax').attr('src',imgSrc).show();
    });
    //如果是已处理的，则不允许再修改
    $('#dealStatus input,#dealResult,#btnFbDeal').attr('disabled',dealStatus == '2' ? 'disabled' : false);
}

/**
 * 处理反馈结果
 */
function dealFeedback() {
    let dealResult = $('#dealResult').val(), dealStatus = $('input[name="dealStatus"]:checked').val();
    if (isNull(dealResult)){
        alert('处理结果不能为空');
        return;
    }
    if (isNull(dealStatus)){
        alert('请选择处理的状态');
        return;
    }
    $.ajax({
        type: "POST",
        url: '/sameCityFeedback/dealFeedback',
        dataType:'json',
        data: {dealResult: dealResult,newDealStatus: dealStatus,fbId: editFbId},
        cache: true,
        success: function(editRow){
            if (editRow < 1){
                swal('成功提示','处理失败','error');
                return;
            }
            reloadFeedback();
            swal('成功提示','处理成功','success');
            closeFbForm();
        },
        error: function (e) {
            swal('失败提示','处理时出错，原因：' + e,'error');
        }
    });
}
function closeFbForm() {
    $('.page-mask,.feedback-from').hide();
}

/**
 * 重新加载反馈内容数据
 */
function reloadFeedback() {
    let fbParam = {
        fbContact: $('#qContact').val(),
        fbType: $('#qType').val(),
        dealStatus: $('#qStatus').val(),
        startDate: $('#qFbStartDate').val(),
        endDate: $('#qFbEndDate').val()
    };
    jQuery(fbGridSelector).setGridParam({postData:fbParam}).trigger("reloadGrid");
}